`
https://leetcode.cn/problems/next-greater-element-ii/
`

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var nextGreaterElements = function (nums) {
  const n = nums.length
  const res = new Array(n).fill(0)
  const stack = []

  // 遍历两次数组来模拟环形数组
  for (let i = 2 * n - 1; i >= 0; i--) {
    const num = nums[i % n]
    while (stack.length && num >= stack[stack.length - 1]) {
      stack.pop()
    }
    res[i % n] = stack.length ? stack[stack.length - 1] : -1
    stack.push(nums[i % n])
  }

  return res
};